
#include <p18f4550.h>
#include <delays.h>
#include <math.h>
//#include "dataTypes.h"
#pragma config FOSC = INTOSCIO_EC //Internal oscillator, port function on RA6, EC used by USB 
#pragma config WDT = OFF //Disable watchdog timer

void interruptHandler(void);
volatile int direccion=1;
#pragma code high_vector=0x08
void highInterrupt(void)
{
_asm GOTO interruptHandler _endasm	
}
#pragma code

#pragma interrupt interruptHandler
void interruptHandler()
{
 if(direccion=0)
{direccion=1;}
else
{direccion=0;}
LATD=0XFF;
Delay10KTCYx(ADRESH);
LATD=0X1;
INTCONbits.INT0IF=0;


}
unsigned char transitions[8][4]=
{1,0,7,0,
 2,1,0,1,
 3,2,1,2,
 4,3,2,3,
 5,4,3,4,
 6,5,4,5, 
 7,6,5,6, 
 0,7,6,7
};
unsigned char power(unsigned char state)
{
	switch(state)
	{
	case 0:
	return 1;
	break;

	case 1:
	return 2;
	break;

	case 2:
	return 4;
	break;

	case 3:
	return 8;
	break;

	case 4:
	return 16;
	break;

	case 5:
	return 32;
	break;

	case 6:
	return 64;
	break;

	case 7:
	return 128;
	break;

	default:
	return 255;
	break;
	}	
}

void initializeADC(void)
{OSCCONbits.SCS0 = 0;
    OSCCONbits.SCS1 = 1; 
    OSCCONbits.IRCF0 = 1;
    OSCCONbits.IRCF1 = 1;
    OSCCONbits.IRCF2 = 1;

    OSCCONbits.IDLEN = 0;

//ADCON0 CONFIGURATION
	//Select channel 0 CHS3:CHS0 -> 0000
	ADCON0bits.CHS3=0;
	ADCON0bits.CHS2=0;
	ADCON0bits.CHS1=0;
	ADCON0bits.CHS0=0;
	//Enable ADC
	ADCON0bits.ADON=1;	

	//ADCON1 CONFIGURATION
	ADCON1bits.VCFG1=0; //use VSS as - reference
	ADCON1bits.VCFG0=0;	//use VDD as + reference
	ADCON1bits.PCFG3=1;
	ADCON1bits.PCFG2=1;
	ADCON1bits.PCFG1=1;
	ADCON1bits.PCFG0=0;

	//ADCON2 CONFIGURATION
	ADCON2bits.ADFM=0;
	//Select 2TAD
	ADCON2bits.ACQT2=0;
	ADCON2bits.ACQT1=0;
	ADCON2bits.ACQT0=0;
	//select FRC (clock derived from A/D RC oscillator)
	ADCON2bits.ADCS2=0;
	ADCON2bits.ADCS1=0;
	ADCON2bits.ADCS0=0;
    //configure pin 2 as input
	//TRISAbits.TRISA0=1;
    //set pin 20 as output
	//TRISDbits.TRISD1=0;
	TRISD=0X00;
	TRISC=0xFF;
//interrupts
INTCONbits.GIE=0;//global interrupts enables
//INTCONbits.INT0IE1=0;//external interrupt 0 enabled
INTCON2bits.INTEDG0=0;//int0 triggers on rising edge

}


void main()
{
int delay;
unsigned char state=0;
unsigned char entry=0;
initializeADC();
LATC=0;
LATD=(unsigned char)pow(2,state);
//Delay10KTCYx(128);
while(1){
LATC=PORTC;

ADCON0bits.GO_DONE = 1;//Start A/D Conversion
while(ADCON0bits.GO_DONE );//Loop here until A/D conversion completes
delay = ADRESH;
entry=LATC&0X03;
state=transitions[state][entry];
LATD=power(state);
Delay10KTCYx(delay);



}

		

}